package me.chan.sort;

import static me.chan.util.SortUtil.*;

/**
 * Created by JanGin on 2017/9/10.
 */
public class InsertionSort {

    private InsertionSort(){}

    public static void sort(Comparable[] arr) {
        int len = arr.length;
        for (int i = 1; i < len; i++) {
            for (int j=i; j > 0 && less(arr[j], arr[j-1]); j--) {
                exch(arr, j, j-1);
            }
        }
    }

    public static void sortWithSentinel(Comparable[] arr) {
        int len = arr.length;
        int min = 0;
        for (int i = 1; i < len; i++) {
            if (less (arr[i], arr[min])) {
               min = i;
            }
        }
        exch(arr, 0, min);

        for (int i = 2; i < len; i++) {
            for (int j = i; less(arr[j], arr[j-1]); j--) {
                exch(arr, j, j-1);
            }
        }
    }


    public static void sortWithNoExch(Comparable[] arr) {
        int len = arr.length;
        for (int i = 2; i < len; i++) {
            System.out.println("arr[0]==" + arr[0]);
            if (less(arr[i], arr[i-1])) {
                arr[0] = arr[i];
                int j;
                for (j = i - 1; less(arr[0], arr[j]); j--) {
                    arr[j + 1] = arr[j];
                }
                arr[j + 1] = arr[0];
            }
        }
    }

    public static void main(String[] args) {
        Integer[] arr = {20, 17, 12, 9, 10, 23, 13, 24, 19, 93, 8, 15, 98, 4, 68 };

        //before sorted
        show(arr);  //[ 20, 17, 12, 9, 10, 23, 13, 24, 19, 93, 8, 15 ]

        sortWithSentinel(arr);
        //after sort
        show(arr);  //[ 8, 9, 10, 12, 13, 15, 17, 19, 20, 23, 24, 93 ]

    }
}
